<template>
  <div class="domain-detail">
    <el-form ref="form" :rules="rules" :model="form"  label-width="180px" size="media" :disabled="ifFind">
      <el-row :gutter="10">
        <el-col :span="9" v-show="ifFind">
          <el-form-item label="ID" prop="ID">
            <el-input v-model.trim="form.ID" prefix-icon="el-icon-info" style="width:100%" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="9" v-show="ifFind">
          <el-form-item label="创建时间" prop="CreatedAt">
            <el-input v-model="form.CreatedAt" prefix-icon="el-icon-info" style="width:100%" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="域名" prop="domain_name">
            <el-input placeholder="www.baidu.com" v-model.trim="form.domain_name" @input="fillDomainIndex"  style="width:100%" prefix-icon="el-icon-info"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="协议" prop="protocol" style="width:100%" >
            <el-select clearable placeholder="请选择" v-model="form.protocol" @change="fillDomainIndex" style="width:100%">
              <el-option label="http" value="http"></el-option>
              <el-option label="https" value="https"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9">
          <el-form-item label="域名首页" prop="domain_index">
            <el-input v-model.trim="form.domain_index" style="width:100%" prefix-icon="el-icon-info"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="环境" prop="env" style="width:100%" >
              <el-select  placeholder="环境" v-model="form.env" style="width:100%">
                <el-option
                        v-for="(item, i) in envOptions"
                        :key="i"
                        :label="item.item_name"
                        :value="item.item_value"
                ></el-option>
                </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9">
          <el-form-item label="外网IP" prop="external_ip">
            <el-input v-model.trim="form.external_ip" prefix-icon="el-icon-info" style="width:80%"/>
            <el-button type="primary" icon="el-icon-search" @click="resolveIP('external')" style="width:20%">解析</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="外网端口" prop="external_port">
            <el-input v-model.trim="form.external_port" @input="fillDomainIndex" prefix-icon="el-icon-info" style="width:80%"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="内网IP(一般是内网VIP)" prop="internal_ip">
            <el-input v-model.trim="form.internal_ip" prefix-icon="el-icon-info" style="width:80%"/>
<!--            <el-button type="primary" icon="el-icon-search" @click="resolveIP('internal')" style="width:20%">解析</el-button>-->
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="内网端口" prop="internal_port">
            <el-input v-model.trim="form.internal_port" prefix-icon="el-icon-info" style="width:80%"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="ICP备案号" prop="icp_number">
            <el-input v-model.trim="form.icp_number" prefix-icon="el-icon-info" style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="公安备案号" prop="ga_number">
            <el-input v-model.trim="form.ga_number" prefix-icon="el-icon-info" style="width:100%"/>
          </el-form-item>
        </el-col>

        <el-col :span="9">
          <el-form-item label="项目归属" prop="project_code" style="width:100%">
            <el-select  clearable filterable placeholder="请选择项目归属"  v-model="form.project_code" style="width:100%">
              <el-option
                      v-for="(item, i) in projectOptions"
                      :key="i"
                      :label="item.project_fullname"
                      :value="item.project_code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="过期日期" prop="expire_time" style="width:100%">
            <el-date-picker
                    v-model="form.expire_time"
                    type="date"
                    placeholder="选择日期" style="width:100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                      v-for="dict in statusOptions"
                      :key="dict.item_value"
                      :label="dict.item_value |formatBoolean"
              >{{ dict.item_name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="bottom-button" style="display: block;margin-left: 180px;width: 120px">
      <el-button v-if="!ifFind" type="primary" size="medium" @click="onSubmit">保存</el-button>
      <el-button v-else :disabled="true" type="primary" size="medium" @click="onSubmit">保存</el-button>
      <el-button size="medium" @click="goBack">取消</el-button>
    </div>

  </div>
</template>

<script>
  import {
    getDomainById,
    createDomain,
    updateDomain,
  } from "@/api/cmdb_domain";
  import { getProjectList }  from "@/api/cmdb_project";
  import { formatTimeToStr } from '@/utils/date';
  import infoList from '@/mixins/infoList';
  import { resolverIP }  from "@/api/dns";


  export default {
    name: "domainDetail",
    mixins: [infoList],
    data() {
      return {
        projectOptions: [],
        statusOptions:[],
        envOptions: [],
        form: {
          ID: '',
          domain_name: '',
          protocol: 'https',
          domain_index: '',
          external_ip: '',
          external_port: '',
          internal_ip: '',
          internal_port: '',
          project_code:'',
          project_name:'',
          icp_number:'',
          ga_number:'',
          env:'prod',
          expire_time: new Date(),
          CreatedAt: null,   // 不能设置成 ''  时间格式要传递post到后端
          status: true,
        },
        ifFind: false,
        // 操作类型
        opType: '',   // find|edit|crate
        rules: {
          domain_host: [{ required: true, message: '域名', trigger: 'blur' }],
          protocol: [{ required: true, message: '请正确输入项目名称', pattern: /^[a-z|-]*$/,trigger: 'blur' }],
          expire_time: [{required: true, message: '请选择时间',trigger: 'blur' }],
        },
      }
    },
    filters: {
      formatDate: function(time) {
        if (time != null && time != '') {
          var date = new Date(time)
          return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      },
      formatBoolean: function(s) {
        if (s == "1" ) {
          return true
        } else {
          return false;
        }
      },

    },
    created() {
      const id = this.$route.query.id
      if (id != null) {
        this.queryDetail(id)
      }
      // 路由参数(页面操作类型) find|create|edit
      this.opType = this.$route.query.type
      if (this.opType == 'find') {
        this.ifFind = true
      }

      this.statusOptions = this.getDicItemList('sys_common_status')

      if (this.opType != 'find') {
        this.envOptions = this.getDicItemList('env_name')
      }

      getProjectList({'page':1, 'pageSize': 999}).then(response => {
        this.projectOptions = response.data.list;
      })


    },
    methods: {
      queryDetail(id) {
        getDomainById({id: parseInt(id)}).then(res => {
          if (res.code == 0) {
            this.form = res.data.domain
          }
        })
      },
      async createDomain(){
        createDomain(this.form).then(res => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '创建成功',
            })
            this.$router.push({ name: 'domain'})
          }
        })
      },
      updateDomain() {
        updateDomain(this.form).then(res => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '更新成功',
            })
            this.$router.push({ name: 'domain'})
          }
        })

      },
      goBack() {
        this.$router.go(-1)
      },
      onSubmit() {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            return
          }
          // 编辑 提交
          if (this.opType == 'edit') {
            this.updateDomain()

            // 新建
          } else if (this.opType == 'create') {
            this.createDomain()
          } else {
            this.$message({
              type: 'error',
              message: '未知操作类型',
            })
          }
        })
      },
      resolveIP(ipType) {
        resolverIP({ipType:ipType,domainName: this.form.domain_name}).then(res => {
          if (res.data.ips.length != 0) {
            const firstIP = res.data.ips[0]
            if (ipType == 'external') {
              this.form.external_ip = firstIP
            } else {
              this.form.internal_ip = firstIP
            }
          } else {
            this.$message({
              type: 'error',
              message: '域名解析失败, IP地址请手动输入!',
            })
          }
        })
      },
      fillDomainIndex() {
        if (this.form.external_port == "80" || this.form.external_port == "443" || this.form.external_port == "") {
           this.form.domain_index = this.form.protocol + '://' + this.form.domain_name
        }else {
          this.form.domain_index = this.form.protocol + '://' + this.form.domain_name + ':' + this.form.external_port
        }
      }

    }
  }
</script>

<style scoped lang="scss">

</style>
